package cn.ecut.dao;

import cn.ecut.exception.DaoException;
import cn.ecut.model.Comment;
import cn.ecut.model.User;
import cn.ecut.util.JDBCHelper;
import cn.ecut.util.TableNames;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentDao {
    public boolean AddComment(Comment comment){
        String sql="inset into"+ TableNames.COMMENT_TABLE_NAME+"(newsid,userid,username,context,time) values (?,?,?,?,?)";
        return JDBCHelper.execute(sql,comment.getNewsid(),comment.getUserid(),comment.getUsername(),comment.getContext(),comment.getTime());
    }

    public List<Comment> CommentList(Integer begin,String newsid) {
        String sql="select username,context,time,zan from"+TableNames.COMMENT_TABLE_NAME+"where newsid= ? order by time limit ? , ?";
        ResultSet resultSet=JDBCHelper.query(sql,newsid,begin,begin+7);
        List<Comment> comments=warp(resultSet);
        return comments;
    }
    public boolean AddLikes(String id){
        String sql="Update"+TableNames.COMMENT_TABLE_NAME+"set zan=zan+1 where id = ?";
        return JDBCHelper.execute(sql,id);
    }

    private List <Comment> warp(ResultSet resultSet) throws DaoException {
        List<Comment> list=new ArrayList<>();
        try {
            while(resultSet.next()){
                Comment comment=new Comment();
                comment.setUsername(resultSet.getString("userid"));
                comment.setContext(resultSet.getString("context"));
                comment.setTime(resultSet.getTimestamp("time"));
                comment.setZan(resultSet.getInt("zan"));
                list.add(comment);
            }
        } catch (SQLException e) {
            throw new DaoException("数据封装出错。");
        }
        return list;
    }
}
